package main

import (
	"google.golang.org/grpc"
	pb "./friday"
	"./connect"
	"fmt"
	"sync"
)

const (
	address = "127.0.0.1:10023"
)

func main(){
	conn, err := grpc.Dial(address, grpc.WithInsecure())
	if err != nil {
		fmt.Println("did not connect: %v", err)
	}
	defer conn.Close()

	// 创建连接
	factory := func() (interface{}, error) {
		return pb.NewDataClient(conn),nil
	}
	// 关闭链接，此处只是定义不需要调用了因为上面有defer conn.Close()，定义的目的在于初始化链接池。
	close := func(v interface{}) error { return conn.Close()}

	//初始化链接池
	p,err := connect.InitThread(10,30, factory, close)
	if err != nil{
		fmt.Println("init error")
		return
	}

	var wg sync.WaitGroup
	for i := 0;i < 5;i++ {
		wg.Add(1)
		go func(){
			defer wg.Done()
			//获取连接
			v,_ := p.Get()
			client := v.(pb.DataClient)
			info := &pb.UserInfoRequest{
				Uid:10012,
			}
			connect.GetUserInfo(client,info)
			//归还链接
			p.Put(v)
		}()
		wg.Wait()
	}

	for i := 0;i < 5;i++ {
		wg.Add(1)
		go func(){
			defer wg.Done()
			//获取连接
			v,_ := p.Get()
			client := v.(pb.DataClient)
			connect.ChangeUserInfo(client)
			//归还链接
			p.Put(v)
		}()
		wg.Wait()
	}
	//获取链接池大小
	current := p.Len()
	fmt.Println("len=", current)
}
